package com.jiangyg.mall.authz.support;

import com.jiangyg.mall.authz.constant.SecurityConstant;
import com.jiangyg.mall.authz.enums.ClientType;
import com.jiangyg.mall.core.utils.Logger;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 类描述：鉴权常用工具类
 *
 * @author jiangyg
 * @date 2022-09-03
 */
@Slf4j
public final class AuthzUtils {

    /**
     * 功能描述：返回token信息
     *
     * @param response 响应
     * @param token    token
     */
    public static void writeToken(HttpServletResponse response, String token) {
        response.addHeader(SecurityConstant.tokenName(), token);
        response.addHeader("Access-Control-Expose-Headers", SecurityConstant.tokenName());
    }

    /**
     * 功能描述：判断请求的客户端类型
     *
     * @param request 请求
     * @return 客户端类型
     */
    public static ClientType clientType(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        final String headerName = SecurityConstant.clientTypeHeaderName();
        Logger.debug(log, () -> String.format("客户端类型header名称：[%s]", headerName));
        final String cid = request.getHeader(headerName);
        Logger.debug(log, () -> String.format("客户端类型[%s]名称：[%s]", headerName, cid));
        return ClientType.decide(cid);
    }

}
